package com.zrm.zfcrpa.configuration.security;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zrm.zfcrpa.dao.mapper.loginMapper.LoginDao;
import com.zrm.zfcrpa.utils.MyJwtUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MyTokenFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    private LoginDao loginDao;

    public MyTokenFilter(AuthenticationManager authenticationManager,LoginDao loginDao){
        this.authenticationManager = authenticationManager;
        this.loginDao = loginDao;
        this.setPostOnly(true);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/auth/login","POST"));
     }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        Map<String,String[]> map = request.getParameterMap();
        String username = map.get("username")[0];
        String password = map.get("password")[0];
        User user = new User(username,password,new ArrayList<>());
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),new ArrayList<>()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
    User user = (User) authResult.getPrincipal();
    Map<String,Object> map = new HashMap<>();
    JSONObject object = loginDao.getUserInfo(user.getUsername());
        List<String> list = user.getAuthorities().stream().map(m->{
            return m.getAuthority();
        }).collect(Collectors.toList());
    String token = MyJwtUtils.createToken(user.getUsername(),list.get(0),object);
    map.put("token",token);
    map.put("userObject",object);
    response.setHeader("Content-Type","text/html;charset=UTF-8");
    response.getWriter().write(new ObjectMapper().writeValueAsString(map));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        Map<String,Object> map = new HashMap<>();
        map.put("code","401");
        map.put("msg","账号或密码错误");
        response.setHeader("Content-Type","text/html;charset=UTF-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(map));
    }
}
